<template>
	<div class="imgPreviewBox" :style="{width,height}">
		<div class="preimage" v-if="imageUrl" :style="'background-image: url('+imageUrl+')'"></div>
		<el-icon v-else>
			<plus />
		</el-icon>
      
		<input type="file" @change='changeFn($event)' :name="name" :disabled='disabled'/>
	</div>
</template>

<script setup>
	import {ref,watch,onMounted} from 'vue'
	import Request from '@/utils/request'
	import {message} from '@/utils/element.js'

	const props = defineProps({
		modelValue:'',
		name: {
			type: String,
			default:() => 'file'
		},
		disabled:{
			type: Boolean,
			default(){
				return false  // 默认
			}
		},
		width:{
			type:String,
			default:()=> '100px'
		},
		height:{
			type:String,
			default:()=> '100px'
		},
		immediately:{ // 是否立即上传
			type: Boolean,
			default:true  
		}
	})
	const emit = defineEmits(['update:modelValue',''])

	const imageUrl = ref('')
	const fileObject = ref('')

	watch(()=>props.modelValue,(newData,oldData)=>{
		imageUrl.value = newData
	})
	onMounted(()=>{
		imageUrl.value = props.modelValue
	})

	const changeFn = e =>{
		let file = e.target.files[0];
		fileObject.value = e.target.files[0]
		if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
			message('只能上传图片',3)
			return false
		}
		if(file.size>3*1024*1000){
			message('图片大小不能超过3M',3)
			return false
		}
		let reader = new FileReader()
		reader.onload = (e) => {
			imageUrl.value = e.target.result
		}
		reader.readAsDataURL(file)

		props.immediately && uploadFile(file) // 立即上传
	}

	const uploadFile = file =>{
		if(!file && !fileObject.value){
			emit('update:modelValue','')
			return
		}
		!file && (file = fileObject.value)
		return new Promise((resolve, reject) =>{
			let fromData = new FormData()
			fromData.append('file', file)
			fromData.append('bucket', 'service')
			let config = {
				headers: {
					'Content-Type': 'multipart/form-data'
				}
			}
			let upUrl = '/file/saveFile'
			Request.post(upUrl,fromData,config)
			.then(res =>{
				if(res.code == 0){
					imageUrl.value = res.data.url//import.meta.env.VITE_BASE_API+'/'+res.data.bucket+res.data.path+'/'+res.data.storeName
					emit('update:modelValue',imageUrl.value)
					resolve(imageUrl.value)
				}else{
					message(res.msg || '上传图片错误，请重试',3)
				}
				console.log("imageUrl:",imageUrl.value)
				
			})
			.catch(err => {
				console.log(err)
				resolve(false)
			})
		})
	}
	defineExpose({uploadFile})  // 导出方法，父组件调用

</script>



	


<style lang="scss">
	.imgPreviewBox {
		display: inline-block;
		width: 100px;
		height: 100px;
		border: 1px dashed #E0E0E0;
		position: relative;
		z-index: 10;
		overflow: hidden;
		text-align: center;
		background: #eee;
		border-radius:2px;
		.preimage{
			width: 100%; 
			height: 100%; 
			left: 0; 
			top: 0; 
			position: absolute;
			z-index: 10;
			background-position: left top;
			background-size: cover;
		}
		i{
			font-size: 40px;
			color: #b4b0b0;
			margin: 33px 0 0 0;
		}
		input{
			width: 100%;
			height: 100%;
			position: absolute;
			z-index: 15;
			left: 0;
			top: 0;
			opacity: 0;
			cursor: pointer;
			&:disabled{
				cursor: not-allowed;
			}
		}
	}
</style>
